package com.he.hsdyc.controller;

import com.he.hsdyc.entity.Member;
import com.he.hsdyc.entity.Result;
import com.he.hsdyc.entity.msg.ErrorCode;
import com.he.hsdyc.entity.msg.Message;
import com.he.hsdyc.entity.vo.MemberVO;
import com.he.hsdyc.enumeration.ResultCode;
import com.he.hsdyc.service.MemberService;
import com.he.hsdyc.service.MyUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.security.Principal;
import java.util.Map;

/**
 * 〈会员Controller〉
 *
 * @author Curise
 * @create 2018/12/13
 * @since 1.0.0
 */
@RestController
@RequestMapping("/api")
public class MemberController {

    @Autowired
    private MyUserDetailService userDetailService;

    @Autowired
    private ConsumerTokenServices consumerTokenServices;

    @Autowired
    private MemberService memberService;

    @GetMapping("/member")
    public Principal user(Principal member) {
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        String name1 = member.getName();
        System.out.println(name);
        System.out.println(name1);
        //获取当前用户信息
        return member;
    }

//    @GetMapping("/current")
//    public String getMember(HttpServletRequest request) {
//        //获取当前用户信息
//        Member member = TokenUtils.analysisToken(request);
//        return member.getMemberName();
//    }

    @DeleteMapping(value = "/exit")
    public Result revokeToken(String access_token) {
        //注销当前用户
        Result result = new Result();
        if (consumerTokenServices.revokeToken(access_token)) {
            result.setCode(ResultCode.SUCCESS.getCode());
            result.setMessage("注销成功");
        } else {
            result.setCode(ResultCode.FAILED.getCode());
            result.setMessage("注销失败");
        }
        return result;
    }


    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Map<?,?> login(@RequestBody MemberVO vo) throws Exception{
        return memberService.login(vo.getMemberName(), vo.getPassword());
    }



    @RequestMapping(value = "/register",method = RequestMethod.POST )
    public Message register(@Valid @RequestBody MemberVO vo) throws Exception {
        memberService.insertUser(vo);
        return new Message(ErrorCode.SUCCESS);
    }

    @RequestMapping(value = "/test",method = RequestMethod.GET )
    public Message test() {
        return new Message(ErrorCode.SUCCESS);
    }
}
